home *** CD-ROM | disk | FTP | other *** search
- Path: solon.com!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c,comp.lang.c.moderated
- Subject: Re: Integral promotion problem
- Date: 10 Mar 1996 19:29:46 -0600
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Sender: clc@solutions.solon.com
- Approved: clc@solutions.solon.com
- Message-ID: <4hvvmb$oqd@solutions.solon.com>
- References: <4hqedq$1mj@solutions.solon.com>
- NNTP-Posting-Host: solutions.solon.com
-
- In article <4hqedq$1mj@solutions.solon.com>,
- John Bain <johnb@pivotal-dm.ccmail.compuserve.com> wrote:
- >Hi,
- >
- >I thought I understood integral promotion, but the following example has
- >me puzzled.
- >
- >--------------------
- >#include <stdio.h>
- >
- >unsigned short s = 0xFFFF;
- >
- >int main(void)
- >{
- > int i = ~s;
-
- Converting an unsigned type to a signed type is implementation defined if that
- signed type is not large enough to represent all the values of the signed
- (which it may not be in this case). In the expression ~s, the s is first
- promoted to an int in an implementation whose int can hold all the values of an
- unsigned short. Otherwise it is converted to an unsigned int. If the latter is
- the case, upon assigning the unsigned int type to the integer i you are calling
- for implementation-defined behavior.
-
- > printf ("%x %x\n", i, (int)~s);
-
- The same caveat applies here, due to the cast to (int).
-
- > if (i)
- > printf("i - NonZero\n");
- > else
- > printf("i - Zero\n");
- >
- > if ((int)~s)
- > printf("(int)~s - NonZero\n");
- > else
- > printf("(int)~s - Zero\n");
- >
- > return 0;
- >}
- >--------------------
- >
- >When compiled on an implementation with 32-bit 2's complement ints I get
- >the following output:
- >
- >-------------------
- >ffff0000 ffff0000
- >i - NonZero
- >(int)~s - Zero
- >------------------
- >
- >The hex values and the result of the first "if" are the "surprising"
- >results I was expecting. However, the result of the second "if" has me
- >confused.
- >
- >What am I missing?
-
- A compiler that works?
-
- >(In case it's relevent, the implementation defines the conversion of an
- >unsigned integer to a signed integer, when the unsigned value cannot be
- >represented in the signed integer, as being performed by truncation of
- >the most significant bits if the signed integer is shorter, and then
- >interpreting the remaining bits as a 2's complement integer.)
-
- But what is the size of short on that implementation? If unsigned shorts are
- 16-bits, and ints are 32-bits, then in the expression ~s, the s goes first to
- an int (which _can_ hold all the values of an unsigned short). The resulting
- int is then inverted bitwise (an operation which, incidentally, affects the
- _value_ in an implementation-specific way).
- --
-